package com.xiashitech.agent.instrumentation.biz.desensitization.httpurl.struts;

import com.xiashitech.agent.config.StartConfig;
import com.xiashitech.agent.dto.UserRequest;
import com.xiashitech.agent.instrumentation.base.AbstractAttributesExtractor;
import com.xiashitech.agent.instrumentation.httprequest.XSHttpServletResponseWrapper;
import com.xiashitech.agent.instrumentation.utils.BaggageUtil;
import com.xiashitech.agent.service.DesensitizeService;
import io.opentelemetry.javaagent.shaded.io.opentelemetry.api.baggage.Baggage;
import io.opentelemetry.javaagent.shaded.io.opentelemetry.api.common.AttributesBuilder;
import io.opentelemetry.javaagent.shaded.io.opentelemetry.context.Context;
import org.jetbrains.annotations.Nullable;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class XSActionInvocationAttributesExtractor extends AbstractAttributesExtractor<UserRequest, HttpServletResponse> {

    @Override
    public void onXSStart(AttributesBuilder attributesBuilder, Context context, UserRequest userRequest) {
        try{
            Baggage baggage = Baggage.fromContext(context);
            HttpServletRequest httpRequest = (HttpServletRequest) userRequest.getRequest();
            if (httpRequest == null) return;
            userRequest.setEndpointApi(httpRequest.getRequestURI());
            attributesBuilder.put("xs.userId",baggage.getEntryValue("xs.userId"));
            attributesBuilder.put("xs.systemId", StartConfig.getParamValueFromKey(StartConfig.systemId));
        }catch (Throwable e){
            StartConfig.throwableStackPrinter(e);
        }
    }

    @Override
    public void onXSEnd(AttributesBuilder attributesBuilder, Context context, UserRequest userRequest, @Nullable HttpServletResponse response, @Nullable Throwable throwable) {
        try {
            HttpServletRequest httpRequest = (HttpServletRequest)userRequest.getRequest();
            if (httpRequest == null) return;
            if (response instanceof XSHttpServletResponseWrapper && response.getContentType().toLowerCase().contains("json")) {
                XSHttpServletResponseWrapper xsResponse = (XSHttpServletResponseWrapper) response;
                String oriJson = DesensitizeService.getResponseJsonData(xsResponse);
                DesensitizeService.desensitizeResponseJsonData(userRequest, xsResponse, oriJson);
            }
        } catch (Throwable e) {
            StartConfig.throwableStackPrinter(e);
        }
    }

    @Override
    public String getAttributesExtractorName() {
        return XSActionInvocationAttributesExtractor.class.getName();
    }
}
